global class SelectMasterClientController {

    public String retUrl{ get; set; }

    //accountid passed in querystring from account page
    String accountId     = ApexPages.currentPage().getParameters().get('accid');
    //accountid passed in querystring from lead page
    String leadId        = ApexPages.currentPage().getParameters().get('leadid');
    //entity type passed in querystring from account page
    String ent           = ApexPages.currentPage().getParameters().get('ent');
       
    string recordTypeAASSalesAccount= RecordTypeHelper.GetRecordTypeId('Account', 'AAS Sales Account'); 
    

    public SelectMasterClientController(ApexPages.StandardController controller) {
            retUrl        = ApexPages.currentPage().getParameters().get('RetURL');     
            retUrl        = EncodingUtil.urlDecode(retUrl  , 'UTF-8');            
            RecordTypeHelper.SetRecordTypeIncaseNotSet(ent);
    }
    

    // Init cLongDate with the current Datetime in long date format    
    public String getLongDate() {
        Datetime cDT = System.now();
        return cDT.format('yyyyMMdd');
    
    }
     @RemoteAction
     global static String getSalesAccount(string agency, string master) { 
        Account[] accounts =  [select id, name from account where AAS_Agency_Name__c= :agency and Master_Client__c= :master 
                 Limit 1];
           if( accounts.size() > 0 )
           { 
                return accounts[0].name;
           }
        return 'New';     
}

    public PageReference init(){

      //check for default values ,if coming from account page 
      if(accountId != null) 
          return loadDefaultValues(); 

      //stay in this page    
      return null;
       

    }    
     
     //this method will get called only when the opportunity wizard is called from account page
     private PageReference loadDefaultValues(){
     
         try
         {
         Account account = [ SELECT  
                                     id, name, recordtype.name,
                                     AAS_Agency_Name__c,Master_Client__c,
                                     AAS_Agency_Name__r.Name, Master_Client__r.Name ,
                                     AAS_Agency_ID__c, Master_Client_ID__c    
                                 FROM 
                                     account 
                                 WHERE 
                                     Id= :accountId ];
                                  
          System.Debug('record type' + account.recordtype.name );

         //based on the selected account record type ,set default value or redirect.. 
         if(account.recordtype.name == 'AAS Sales Account') {
            //redirect to AAS Opportunity page ..
            //set parent account name and recordtype of opportunity
            
             
             //string redirectURL = '/006/e?accid=' + account.id + 
             //                   '&nooverride=1&RecordType= ' + 
             //                   RecordTypeHelper.GetRecordTypeId('Opportunity', 'Advanced Ad Solutions') +
             //                   '&retURL=' + retUrl;
           string opportunityNameFirstPart ;
           if(account.Master_Client__r.Name != null && account.Master_Client__r.Name.length() > 45) {
             opportunityNameFirstPart = account.Master_Client__r.Name.substring(0,44);
           }
           else  {
               opportunityNameFirstPart = account.Master_Client__r.Name;
           }
          
           
           string opportunityNameSecondPart;
           if(account.AAS_Agency_Name__r.Name != null && account.AAS_Agency_Name__r.Name.length() > 45) {
             opportunityNameSecondPart = account.AAS_Agency_Name__r.Name.substring(0,44);
           }
           else {
               opportunityNameSecondPart = account.AAS_Agency_Name__r.Name;
           } 

             
            //create the opportunity and redirect to opportunity page
              Opportunity o_rel = new Opportunity(          
                               name = opportunityNameFirstPart + '_' + opportunityNameSecondPart + '_' + getLongDate(),                    
                               recordtypeid=  RecordTypeHelper.GetRecordTypeId('Opportunity', 'Advanced Ad Solutions'),
                               AAS_Agency__c= account.AAS_Agency_Name__c,
                               AAS_Master_Client__c= account.Master_Client__c,
                               accountId= account.id,
                               StageName= 'Proposal Requested by AE',
                               CloseDate = Date.today()+30
                           );
              
             /*
                udpated by Paul Lo, 9/7/11, AD-22214 defaulting AdWorks Opp stage to 10% Ascertainment 
                
                Note:
                Michael Shu suggested to hard code instead of referencing to AAS helper class since it's less confusing to
                relate 2 unrelated classes
             */             
             o_rel.StageName = 'Ascertainment by AE';
              
              Insert o_rel ; 

           //set parent account name and recordtype of opportunity
           string redirectURL = '/' + o_rel.Id + '/e';


            System.Debug(redirectURL ) ; 
            PageReference nextPage = new PageReference(redirectURL);
            nextPage.setRedirect(true);        
            return nextPage;            
         }
         else if(account.recordtype.name == 'AAS Agency'){
               getselectionObject().agencyName = account.Name;
               getselectionObject().agencyId   = account.AAS_Agency_ID__c;
               getselectionObject().agency   =  account.Id;         
         }
         else if(account.recordtype.name == 'AAS Master Client'){  
               getselectionObject().clientName = account.Name;
               getselectionObject().clientId   = account.Master_Client_ID__c;
               getselectionObject().client     =  account.Id;
               System.Debug(account.Name +account.Master_Client_ID__c+account.Id ) ; 
         }
         
        return null; 
        }
        catch (QueryException e){
            throw new SelectMasterClientException(e.getMessage() + ', accountId= ' + accountId);
      }       

         
     }
     public PageReference createOpportunity() {
        //PageReference currentPage = ApexPages.currentPage();          
        //Map<String,String> currentPageParameters = currentPage.getParameters();
        System.debug('response1' + sel_object.agency);
        System.debug('response2' + sel_object.client);       
        System.debug('response3' + sel_object.agencyId);
        System.debug('response4' + sel_object.clientId);        

        System.Debug('response5'+ sel_object.createOpportunity);
        System.Debug('response6'+ sel_object.newClientName);
        System.debug('response7' + sel_object.agencyName);
        System.debug('response8' + sel_object.clientName);        
     
        
        String redirectURL = createObjects();

        PageReference nextPage = new PageReference(redirectURL);
        nextPage.setRedirect(true);        
        return nextPage;
    }
    private string convertLead(Account parentAccount){    
        
        Database.LeadConvert lc = new database.LeadConvert();
        
        //set the leadId to convert from the querystring parameter      
        lc.setLeadId(leadId);
        
        // queries the LeadSource table to obtain all of the possible converted status option
        LeadStatus convertStatus = 
                 [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];               
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        //if create opportunity checkbox is checked
        if(sel_object.createOpportunity =='checked') 
                lc.setDoNotCreateOpportunity(false);  //create 
        else
                lc.setDoNotCreateOpportunity(true);  //do not create
                
        lc.setAccountId(parentAccount.Id);
                    
        //convert lead operation
        Database.LeadConvertResult lcResult = Database.convertLead(lc);
        if (lcResult.isSuccess()) {
            //get the opportunityid /accountid          
            string convertedAccountId       = lcResult.getAccountId();
            string convertedOpportunityId   = lcResult.getOpportunityId();
                if(convertedOpportunityId != null ) {

                    //set the record type of converted opportunity
                    Opportunity convertedOpportunity = [Select id,recordtypeid from Opportunity where id=:convertedOpportunityId];
                    convertedOpportunity.recordtypeid = RecordTypeHelper.GetRecordTypeId('Opportunity', 'Advanced Ad Solutions');
                    update convertedOpportunity;
                    
                    //redirect to opportunity
            return '/' + convertedOpportunityId+'/e';
                }
                else{               
                    return '/' + convertedAccountId;
                }
        }       
        else {
            System.Debug('\nError converting new Lead: ' +   lcResult.getErrors()[0].getMessage());
            return null;
        }
    
    }
     private string createObjects()
     {
     Account a_sa;
     Account a_mc;
     Account parentAccount;
     string redirectURL ;
     System.Debug('opp checked' + sel_object.createOpportunity );
     //new master client- search for client name didnot match with existing accounts.
     if(sel_object.client == '') {
        if(sel_object.newClientName =='')
           System.Debug('new client name is missing ...');
           
             a_mc = new Account(
                              name = sel_object.newClientName,
                              recordtypeid=  RecordTypeHelper.GetRecordTypeId('Account', 'AAS Master Client'),
                              account_status__c = 'Draft',
                              AAS_Agency_Name__c= sel_object.agency
                     ) ;
             Insert a_mc; 
             
             //assign the master client id for opportunity creation
             sel_object.client=a_mc.Id;
             sel_object.ClientName=sel_object.newClientName;
             
             a_sa = new Account(
                              name = sel_object.ClientName + '(' + sel_object.AgencyName + ')',
                              recordtypeid=  recordTypeAASSalesAccount ,
                              account_status__c = 'Draft',
                              AAS_Agency_Name__c= sel_object.agency,
                              Master_Client__c = a_mc.id,
                              AAS_Agency_ID__c =sel_object.agencyId,
                              Master_Client_ID__c =a_mc.Master_Client_ID__c 
                              
                     ) ;  
             Insert a_sa ; 
             parentAccount = a_sa;   
             redirectURL = '/' + a_sa.Id ;   
             System.Debug('redirectURL (in new master)' + redirectURL );                                                                  
       }
       else {
           string nasaId=  sel_object.agencyId + '-' + sel_object.clientId;
           
           //if the combination of agencyid and clientid does not exist, create an AAS sales account
           Account[] accounts =  [select id, name from account where NASA_ID__c= :nasaId and recordtypeid= :recordTypeAASSalesAccount Limit 1];
           if( accounts.size() <= 0 )
           {
                   a_sa = new Account(
                              name = sel_object.ClientName + '(' + sel_object.AgencyName + ')',
                              recordtypeid=  recordTypeAASSalesAccount ,
                              account_status__c = 'Draft',
                              AAS_Agency_Name__c= sel_object.agency,
                              Master_Client__c = sel_object.client
                     ) ;  
                    Insert a_sa ;   
                    parentAccount = a_sa;
                    redirectURL = '/' + a_sa.Id ;  
                    System.Debug('redirectURL (in sales account)' + redirectURL );                                
           }
           else
           {
              parentAccount= accounts[0];
           System.Debug('redirectURL (in parent acc)' + redirectURL );                                              redirectURL = '/' + parentAccount.Id ;  

           }
       }
       
       //convert lead if leadid is passed 
       if(ent == 'Lead'){
           redirectURL = convertLead(parentAccount); 
           System.Debug('redirectURL (in lead convert)' + redirectURL );                                
       }        
       else if( sel_object.createOpportunity =='checked')
       {
           System.debug('parent account->' + parentAccount.Id);
           
           string opportunityNameFirstPart ;
           if(sel_object.ClientName != null && sel_object.ClientName.length() > 45) {
             opportunityNameFirstPart = sel_object.ClientName.substring(0,44);
           }
           else  {
               opportunityNameFirstPart = sel_object.ClientName;
           }
          
           
           string opportunityNameSecondPart;
           if(sel_object.AgencyName != null && sel_object.AgencyName.length() > 45) {
             opportunityNameSecondPart = sel_object.AgencyName.substring(0,44);
           }
           else  {
               opportunityNameSecondPart = sel_object.AgencyName;
           } 

           
           Opportunity o_rel = new Opportunity(
                               name = opportunityNameFirstPart + '_' + opportunityNameSecondPart + '_' + getLongDate(),
                               recordtypeid=  RecordTypeHelper.GetRecordTypeId('Opportunity', 'Advanced Ad Solutions'),
                               AAS_Agency__c= sel_object.agency,
                               AAS_Master_Client__c= sel_object.client,
                               accountId= parentAccount.Id,
                               StageName= 'Proposal Requested by AE',
                               CloseDate = Date.today()+30
                           );
                           
           /*
                udpated by Paul Lo, 9/7/11, AD-22214 defaulting AdWorks Opp stage to 10% Ascertainment 
                
                Note:
                Michael Shu suggested to hard code instead of referencing to AAS helper class since it's less confusing to
                relate 2 unrelated classes
           */             
           o_rel.StageName = 'Ascertainment by AE';
           
           Insert o_rel ; 

           //set parent account name and recordtype of opportunity
           redirectURL = '/' + o_rel.Id+'/e';
          /* redirectURL = '/006/e?accid=' + parentAccount.Id + 
                                '&nooverride=1&RecordType= ' + 
                                RecordTypeHelper.GetRecordTypeId('Opportunity', 'Advanced Ad Solutions');
                                */
           System.Debug('redirectURL (in opp)' + redirectURL );                                
       }
       
       //add the return ul parameter
       if(redirectURL.Contains('?'))
          redirectURL +=  '&retURL=' + retUrl;
       else
          redirectURL +=  '?retURL=' + retUrl;
       System.Debug('redirectURL' + redirectURL ); 
       return redirectURL ;
     }
     
   public class SelectMasterClientException extends Exception {}
 

 
   public class SelectionObject {
    private String newClientName= '';
    public String getNewClientName() { return newClientName; }
    public void setNewClientName(String data) { newClientName= data; }
    
    private String agency = '';
    public String getAgency() { return agency; }
    public void setAgency(String data) { agency = data; }

    private String client = '';
    public String getClient() { return client; }
    public void setClient(String data) { client = data; }
    
    private String agencyId = '';
    public String getAgencyId() { return agencyId; }
    public void setAgencyId(String data) { agencyId = data; }

    private String clientId = '';
    public String getClientId() { return clientId; }
    public void setClientId(String data) { clientId = data; }

    private String agencyName = '';
    public String getAgencyName() { return agencyName; }
    public void setAgencyName(String data) { agencyName = data; }

    private String clientName = '';
    public String getClientName() { return clientName; }
    public void setClientName(String data) { clientName = data; }
    
    private String createOpportunity= '';
    public String getCreateOpportunity() { return createOpportunity; }
    public void setCreateOpportunity(String data) { createOpportunity= data; }
    
  }

  private SelectionObject sel_object;

  public SelectionObject getselectionObject() {
    if (sel_object == null) { sel_object = new SelectionObject(); }
    return sel_object;
    }
}